package org.itt.cp.gdc;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.TreeMap;

import org.apache.log4j.Logger;
import org.itt.FooUtil;
import org.itt.Properties;
import org.itt.ap.Reader;
import org.itt.ap.Source;

public class GdCReader implements Reader {
    private static Logger logger = Logger.getLogger("GdCReader");
    
    public static void printProgBar(long l){
        StringBuilder bar = new StringBuilder("[");

        for(int i = 0; i < 50; i++){
            if( i < (l/2)){
                bar.append("=");
            }else if( i == (l/2)){
                bar.append(">");
            }else{
                bar.append(" ");
            }
        }

        bar.append("]   " + l + "%     ");
        System.out.print("\r" + bar.toString());
    }
    
	@Override
	public void parse(Source source) {
		int counter = 0;
		String line = "";
		BufferedReader br = null;
		GdC gdc = null;
	    
		/*
	     * long progress = 0;
	     */

		try {
			TreeMap<Integer, Source> map = new TreeMap<Integer, Source>();
			logger.debug("Istanzio una hashmap di oggetti GdC");

			long fileSize = new File(Properties.get().WORKDIR + File.separator + Properties.get().SOURCE).length();
            logger.debug("File sorgente: " + Properties.get().WORKDIR + File.separator + Properties.get().SOURCE + " - dimensione: " + fileSize + " bytes");
           
            br = new BufferedReader(new FileReader(Properties.get().WORKDIR + File.separator + Properties.get().SOURCE));
            logger.info("Mi preparo a leggere il file sorgente: " + Properties.get().WORKDIR + File.separator + Properties.get().SOURCE);
           
			long start = System.nanoTime();

			while ((line = br.readLine()) != null) {
				/*
				 * progress += line.length();
				 * printProgBar(progress*100/fileSize);
				 * 
				 */
                
				line = line.trim();

				if (line.startsWith("<")) {
					GdC pec = (GdC) map.get(counter - 1);
					pec.setCompressedDoc(pec.getCompressedDoc() + line);
				} else {
					gdc = new GdC();

					String[] gdcArray = new String[12];

					String[] row = line.split(Properties.get().SPLIT_BY);

					int i;

					for (i = 0; i < gdcArray.length; i++) {
						gdcArray[i] = "";
					}

					for (i = 0; i < row.length; i++) {
						gdcArray[i] = row[i];
					}
					
					/* ID */
					gdc.setId(Integer.valueOf(gdcArray[0]));
					logger.debug("ID: " + gdc.getId());
					
					/* RECORD_TIME */
					gdc.setRecordTime(new SimpleDateFormat("dd/mm/yyyy hh:mm:ss").parse(gdcArray[1]));
					logger.debug("RECORD_TIME: " + gdc.getRecordTime());

					/* CALLER_ID */
					gdc.setCallerId(gdcArray[2]);
					logger.debug("CALLER_ID: " + gdc.getCallerId());

					/* CALLER_NAME */
					gdc.setCallerName(gdcArray[3]);
					logger.debug("CALLER_NAME: " + gdc.getCallerName());
					
					/* CALLER_SURNAME */
					gdc.setCallerSurname(gdcArray[4]);
					logger.debug("CALLER_SURNAME: " + gdc.getCallerSurname());
					
					/* CALLER_COUNTRY */
					gdc.setCallerCountry(gdcArray[5]);
					logger.debug("CALLER_COUNTRY: " + gdc.getCallerCountry());

					/* CALLER_FISCALCODE */
					gdc.setCallerFiscalcode(gdcArray[6]);
					logger.debug("CALLER_FISCALCODE: " + gdc.getCallerFiscalcode());

					/* DOMAIN */
					gdc.setDomain(gdcArray[7]);
					logger.debug("DOMAIN: " + gdc.getDomain());

					/* SERVICE_NS */
					gdc.setServiceNS(gdcArray[8]);
					logger.debug("SERVICE_NS: " + gdc.getServiceNS());
					
					/* OPERATION */
					gdc.setOperation(gdcArray[9]);
					logger.debug("OPERATION: " + gdc.getOperation());
						
					/* RESULT */
					gdc.setResult(Integer.valueOf(gdcArray[10]));
					logger.debug("RESULT: " + gdc.isResult());
					
					/* COMPRESSED_DOC */
					if (gdcArray[11] != null) {
						gdc.setCompressedDoc(gdcArray[11]);
						logger.trace("COMPRESSED_DOC: " + gdc.getCompressedDoc());
					}

					map.put(counter, gdc);

					counter++;
				}
			}

			/*
			 * printProgBar(100);
			 * System.out.print("\n");
			 * 
			 */
			
            logger.info("Ho letto " + counter + " righe");
            logger.info("Durata lettura: " + FooUtil.prettyPrintTime(System.nanoTime() - start));

			source.setMap(map);
			logger.debug("Finalizzo la hashmap di oggetti GdC");
		} catch (NumberFormatException | IOException | ParseException e) {
			logger.error(e);
            System.exit(1);
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					logger.error(e);
				}
			}
		}
	}
}